// MiafeOneDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MiafeOne.h"
#include "MiafeOneDlg.h"
#include "umfh.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
HWND hDlg;

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
	
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMiafeOneDlg dialog
int icdev;
unsigned char sector;//M1 Card, the sector to operate,range: 0-15
unsigned char block;//M1 Card,the block to operate,range: 0-63

unsigned char sectorS70;//S70 Card, the sector to operate,range: 0-39, 4 blocks each sector the first 32,16 blocks each sector the last 8 
unsigned char blockS70;//S70 Card, the block to operate (0-255),match with the sector 

CMiafeOneDlg::CMiafeOneDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CMiafeOneDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CMiafeOneDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	hDlg=m_list1.m_hWnd;
	cardtype=-1;
}

void CMiafeOneDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CMiafeOneDlg)
	DDX_Control(pDX, IDC_VERIFYCARD, m_btnVerify);
	DDX_Control(pDX, IDC_HALT, m_btnHalt);
	DDX_Control(pDX, IDC_BTN_LOADKEY, m_btnLoadkey);
	DDX_Control(pDX, IDC_BTN_FINDCARD, m_btnFindCard);
	DDX_Control(pDX, IDC_BTN_DEVFUNC, m_btnDevfunc);
	DDX_Control(pDX, IDC_BTN_CARDFUNC, m_btnCardfunc);
	DDX_Control(pDX, IDC_LIST1, m_list1);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CMiafeOneDlg, CDialog)
	//{{AFX_MSG_MAP(CMiafeOneDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BTN_FINDCARD, OnBtnFindcard)
	ON_BN_CLICKED(IDC_BTN_LOADKEY, OnBtnLoadkey)
	ON_BN_CLICKED(IDC_VERIFYCARD, OnVerifycard)
	ON_BN_CLICKED(IDC_BTN_CARDFUNC, OnBtnCardfunc)
	ON_BN_CLICKED(IDC_BTN_DEVFUNC, OnBtnDevfunc)
	ON_BN_CLICKED(IDC_HALT, OnHalt)
	ON_COMMAND(ID_OPEN, OnOpen)
	ON_COMMAND(ID_MENU_UNLINK, OnMenuUnlink)
	ON_COMMAND(ID_MENU_M1, OnMenuM1)
	ON_COMMAND(ID_MENU_S70, OnMenuS70)
	ON_COMMAND(ID_MENU_ULTRALIT, OnMenuUltralit)
	ON_BN_CLICKED(IDC_BTN_CLEAR, OnBtnClear)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMiafeOneDlg message handlers

BOOL CMiafeOneDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	
	icdev=-1;
	sector=3;
	block=12;

	sectorS70=32;
	blockS70=128;

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CMiafeOneDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CMiafeOneDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CMiafeOneDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}



void CMiafeOneDlg::OnBtnFindcard() 
{
	// TODO: Add your control notification handler code here
	if(0==CheckLinkState())
		return ;

	int st;
	CString linstr;
	unsigned long cardsnr;//set the variable point to card serial number to ULONG type

	switch(cardtype)
	{
	case M1:                   //M1 S70  find card
	case S70:
		{
			setcardtype() ;
			st=fw_card(icdev,1,&cardsnr);//Multy card mode
			if(st!=0)
			{
				show("Find Card Error!");
				return;
			}
			else
			{
				show("Find Card Ok!");
				linstr.Format("%u",cardsnr);
				show(linstr);
			}
			break;
		}
	case Ultralight:
		{
			st=fw_request_ultralt(icdev,1);//find card request with mode 1
			st=fw_anticall_ultralt(icdev,&cardsnr);
			st=fw_select_ultralt(icdev,cardsnr);
			
			if(st!=0)
			{
				show("Find Card Error!");
				return;
			}
			else
			{
				show("Find Card Ok!");
				linstr.Format("%u",cardsnr);
				show(linstr);
			}
			break;
		}
	default:
		show("Unkown card,Chose Card First Please!");
		break;
	}
}

void CMiafeOneDlg::OnBtnLoadkey() 
{
	// TODO: Add your control notification handler code here
	if(0==CheckLinkState())
		return ;

	int st;
	unsigned char keyA[6]={0xff,0xff,0xff,0xff,0xff,0xff};

	//load key
	switch(cardtype)
	{
	case M1:    
		st=fw_load_key(icdev,0,sector,keyA);
		break;
	case S70:
		st=fw_load_key(icdev,0,sectorS70,keyA);
		break;
	default:
		show("Invalid Card type!");
		return;
	}
	
	if(st!=0)
		show("Load Key Error!");
	else
		show("Load Key Ok!");
}

void CMiafeOneDlg::OnVerifycard() 
{
	// TODO: Add your control notification handler code here

	if(0==CheckLinkState())
		return ;

	//verify password       
	int st;
	switch(cardtype)
	{
	case M1:
		{
			st=fw_authentication(icdev,0,sector);
			if(st!=0)
				show("Auth Card Error!");
			else
				show("Auth Card Ok!");
			break;
		}
	case S70:
		{
			st=fw_authentication(icdev,0,sectorS70);//authentication the key of 33 setor
			if(st!=0)
				show("Auth Card Error!");
			else
				show("Auth Card Ok!");
			break;
		}
	default:
		show("Unkown card,Chose Card First Please!");
		break;
	}

}

void CMiafeOneDlg::OnBtnCardfunc() 
{
	// TODO: Add your control notification handler code here
	if(0==CheckLinkState())
		return ;

	int st;
	unsigned long value;
    CString linstr;
    
	unsigned char keya[7]={0xff,0xff,0xff,0xff,0xff,0xff};
	unsigned char keyb[7]={0xff,0xff,0xff,0xff,0xff,0xff};
	unsigned char ctrlword[4]={0xFF,0x07,0x80,0x69};
	unsigned char datachar[40]={'3','4','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3'};
	
	
	int i;
	unsigned char databuff[17]={0};
	 
	char databuff2[33]={0};

	switch(cardtype)
	{
	case M1:                                           //M1 Card function test
		{
			//write data  
			for (i=0;i<16;i++)
			{
				databuff[i]='M';
			}
			st=fw_write(icdev,block,databuff);//Write block 1,Note: you should not write key block when testing
			                              //the 4th block is key block,such as 3,4,7
			if(st!=0)
			{
				show("Write Card Error!");
				return;
			}
			else
			{
				show("Write Card Ok!");	
				hex_a((unsigned char *)databuff2,databuff,32);
				show(databuff2);
			}
			
			//Read data
			st=fw_read(icdev,block,databuff);
			if(st!=0)
				show("Read Card Error!");
			else
			{
				show("Read Card Ok!");
				memset(databuff2,0,32);
				hex_a((unsigned char *)databuff2,databuff,32);
				
				show(databuff2);
			}
			
			value=1000;

			st= fw_initval(icdev, block, value);
			if (st!=0)
			{
				show("fw_initval error");
				linstr.Format("%d",st);
				show(linstr);
				return;
			}
			show("fw_initval ok");
			
			value=300;
			st= fw_increment( icdev,block,value);
			if (st!=0)
			{
				show("fw_increment error");
				return;
			}
			st=fw_transfer(icdev,block);
			
			show("fw_increment ok");
			value=200;
			
			st= fw_decrement( icdev,block,value);
			if (st!=0)
			{
				show("fw_decrement error");
				return;
			}
			st=fw_transfer(icdev,block);
			show("fw_decrement ok");
			
			st= fw_readval(icdev,block,&value);
			if (st!=0)
			{
				show("fw_readval error");
				return;
			}
			show("fw_readval ok");
			linstr.Format("%d",value);
			show(linstr);
			
			st= fw_changeb3(icdev,sector,keya,ctrlword,0,keyb)||//should better don't change the parameter 4,5,6, keep the same as original card
				fw_halt(icdev);
			if (st!=0)
			{
				show("fw_changeb3 error");
				linstr.Format("%d",st);
				show(linstr);
				return;
			}
			show("fw_changeb3 ok");
			break;
		}
	case S70:                                           //S70 Card function test
		{

			//case of S70, 128 blocks the first 32 sectors,16 blocks each sector the last 8
			//the last block is key block,Note: should not change this key block when testing

			//setcardtype();//setup card type as typeA

			//Write data   
			for (i=0;i<16;i++)
			{
				databuff[i]='M';
			}
			st=fw_write(icdev,blockS70,databuff);
			if(st!=0)
			{
				show("Write Card Error!");
				return;
			}
			else
			{
				show("Write Card Ok!");	
			//	hex_a((unsigned char *)databuff2,databuff,32);
			//	show(databuff2);
				show(databuff);
			}
			
			//Read data
			memset(databuff,0,32);
			st=fw_read(icdev,blockS70,databuff);
			if(st!=0)
				show("Read Card Error!");
			else
			{
				show("Read Card Ok!");
			//	memset(databuff2,0,32);
			//	hex_a((unsigned char *)databuff2,databuff,32);
			//	show(databuff2);
				show(databuff);
			}
			
			value=1000;
			st= fw_initval(icdev, blockS70, value);
			if (st!=0)
			{
				show("fw_initval error");
				linstr.Format("%d",st);
				show(linstr);
				return;
			}
			show("fw_initval ok");
			
			value=300;
			st= fw_increment( icdev,blockS70,value);
			if (st!=0)
			{
				show("fw_increment error");
				return;
			}
			st=fw_transfer(icdev,blockS70);
			
			show("fw_increment ok");
			value=200;
			
			st= fw_decrement( icdev,blockS70,value);
			if (st!=0)
			{
				show("fw_decrement error");
				return;
			}
			st=fw_transfer(icdev,blockS70);
			show("fw_decrement ok");
			
			st= fw_readval(icdev,blockS70,&value);
			if (st!=0)
			{
				show("fw_readval error");
				return;
			}
			show("fw_readval ok");
			linstr.Format("%d",value);
			show(linstr);
			
			st= fw_changeb3(icdev,sectorS70,keya,ctrlword,0,keyb)//should better don't change the parameter 4,5,6, keep the same as original card
				||fw_halt(icdev);
			if (st!=0)
			{
				show("fw_changeb3 error");
				linstr.Format("%d",st);
				show(linstr);
				return;
			}
			show("fw_changeb3 ok");
			break;
		}
	case Ultralight:
		{

			//Read card
			//read page 0 before read/write
			unsigned char Data[6]={0};
			st=fw_read_ultralt(icdev,0,Data);//Read page 0
			if(st)
			{
				show("fw_read_ultralt Error!");
				return;
			}
			
			
			//Write card
			unsigned char newCardData[5]={0};
			for(int j=0;j<4;j++)
			{
				newCardData[j]='M';
			}
			
			st=fw_write_ultralt(icdev,4,newCardData);//Write page 4
			
			if(st)
			{
				show("fw_write_ultralt Error!");
				return;
			}
			
			show("fw_write_ultralt OK!");

			//test read card

			st=fw_read_ultralt(icdev,4,Data);//Read page 4
			if(st)
			{
				show("fw_read_ultralt Error!");
				return;
			}
			
			show("fw_read_ultralt Ok!");
			show(Data);


			break;
		}
	default:
		show("Unkown card,Chose Card First Please!");
		break;
	}//end of switch

	return;
}

void CMiafeOneDlg::OnBtnDevfunc() 
{
	// TODO: Add your control notification handler code here

	if(0==CheckLinkState())
		return ;

 // Device functions          
	int st;
    CString linstr;
	unsigned char linchar[17];
	unsigned char timestr[17];



    memset(linchar,0,16);
	st= fw_getver(icdev,linchar);//get version of device
	if (st!=0)
	{
		show("fw_getver error");
	    linstr.Format("%d",st);
	    show(linstr);
		return;
	}
	show("fw_getver ok");
	show(linchar);
	
    linchar[0]=0x45;
    linchar[1]=0x75;
    linchar[3]=0x55;
    linchar[4]=0x65;
    linchar[2]=0x35;
	linchar[5]=0;
	st= fw_swr_eeprom(icdev,24,15,linchar);//Write EEPROM
	if (st!=0)
	{
		show("fw_swr_eeprom error");
	    linstr.Format("%d",st);
	    show(linstr);
		return;
	}
	show("fw_swr_eeprom ok");

	linchar[0]=0;
	st= fw_srd_eeprom(icdev,500,5,linchar);//read
	if (st!=0)
	{
		show("fw_srd_eeprom error");
	    linstr.Format("%d",st);
	    show(linstr);
		return;
	}
	show("fw_srd_eeprom ok");
	memset(timestr,0,17);
	hex_a(timestr,linchar,7);
	show(timestr);


 
	st= fw_reset((HANDLE)icdev,2);//Reset of device
	if (st!=0)
	{
		show("fw_reset error");
	    linstr.Format("%d",st);
	    show(linstr);
		return;
	}
	show("fw_reset ok");



    //des test
/*	unsigned char key[]={'1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f',0};
    unsigned char sour[]={'a','b','c','d','e','f','1','2','3','4','5','6','8','7','9','0',0};

	unsigned char dest[16];
	st=fw_des(key,sour,dest,0);
    if (st!=0)
	{
		show("fw_des error");
		return;
	}
	show("fw_des ok");
	dest[16]=0;
	show(dest);

	show(sour);
    sour[0]=0;

	st=fw_des(key,dest,sour,1);
    if (st!=0)
	{
		show("fw_des error");
		return;
	}
	show("fw_des ok");
	sour[16]=0;
	show(sour);*/

}

void CMiafeOneDlg::OnHalt() 
{
	// TODO: Add your control notification handler code here
    int st;
	st=fw_halt(icdev);
    if(st!=0)
   	   show("Halt Card Error!");
    else
	   show("Halt Card Ok!");	


}

void CMiafeOneDlg::show(CString datastr)
{
	m_list1.AddString(datastr);
	m_list1.SetCurSel(m_list1.GetCount()-1);
	MSG message;
	if (::PeekMessage(&message,NULL,0,0,PM_REMOVE))
	{
		::TranslateMessage(&message);
		::DispatchMessage(&message);
	}
}

LRESULT CMiafeOneDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
	// TODO: Add your specialized code here and/or call the base class
	switch(message)
	{
	case WM_INITDIALOG:
		{
		/*	HWND hDlg=this->m_list1.m_hWnd;
			HDC hdc;
			int i;
			TCHAR str[100];
			for(i = 0; i < 100; i++)
			{
				wsprintf(str, "This is a very very very very very long sentence - line %d", i + 1);
				SendDlgItemMessage(IDC_LIST1, LB_ADDSTRING, 0, (LPARAM)str);
				
			}
			SendDlgItemMessage(IDC_LIST1, LB_SETHORIZONTALEXTENT, 500, 0);
			*/
		}
		break;
	}
	return CDialog::WindowProc(message, wParam, lParam);
}

void CMiafeOneDlg::OnOpen() 
{
	// TODO: Add your command handler code here
	icdev=fw_init(100,115200);//the first parameter, 100: USB,0:COM1,1:COM2,2:COM3 ...
	
	if((int)icdev<=0)
	{
		show("Init Com Error!");
	}
	else
	{
		show("Init Com OK!");
	}
	fw_beep((int)icdev,10);

	SetButtonState(true,true,true,true,true,true);

	return;
}

void CMiafeOneDlg::OnMenuUnlink() 
{
	// TODO: Add your command handler code here
	int st;
	st=fw_exit(icdev);
	icdev=0;

	if(st)
		show("fw_exit error!");
	else
		show("fw_exit Ok!");

	SetButtonState(false,false,false,false,false,false);
}

void CMiafeOneDlg::SetButtonState(bool sloadkey, bool sfindcard, 
								  bool devfunc, bool sverify, 
								  bool scardfunc, bool shalt)
{
	m_btnLoadkey.EnableWindow(sloadkey);
	m_btnFindCard.EnableWindow(sfindcard);
	m_btnCardfunc.EnableWindow(scardfunc);
	m_btnVerify.EnableWindow(sverify);
	m_btnDevfunc.EnableWindow(devfunc);
	m_btnHalt.EnableWindow(shalt);
}

void CMiafeOneDlg::OnMenuM1() 
{
	// TODO: Add your command handler code here
	cardtype=M1;
	SetButtonState(true,true,true,true,true,true);
}

void CMiafeOneDlg::OnMenuS70() 
{
	// TODO: Add your command handler code here
	cardtype=S70;
	SetButtonState(true,true,true,true,true,true);
}

void CMiafeOneDlg::OnMenuUltralit() 
{
	// TODO: Add your command handler code here
	cardtype=Ultralight;
	SetButtonState(true,true,true,false,true,true);
}

void CMiafeOneDlg::OnBtnClear() 
{
	// TODO: Add your control notification handler code here
	m_list1.ResetContent();
}

void CMiafeOneDlg::setcardtype()
{

	int st;
	st=fw_config_card((HANDLE)icdev,0x41);
	if(st)
	{
		show("fw_config_card Error!");
		return;
	}
	show("fw_config_card OK!");
}

int CMiafeOneDlg::CheckLinkState()
{
	if(icdev<=0)
	{
		show("Device is not Linked now!");
		return 0;
	}
	else
		return 1;
}
